//下载升级包
var fm = null;
const rootPath = wx.env?wx.env.USER_DATA_PATH:null;
const fireWare = "bleDriver";
const localFilePath = rootPath + "/" + fireWare + "/fireWare.zip";
const localUnzipFilePath = rootPath + "/" + fireWare + "/fireWare";
var ConstantData = require('../../common/constant_data.js')
var app = getApp();

var dfuPackage = {
  datData:new ArrayBuffer(),
  binData:new ArrayBuffer()
}

function downloadZip() {
  if(rootPath==null){
    return;
  }
  fm = wx.getFileSystemManager();
  return new Promise((resolve, reject) => {
    let path = rootPath + "/" + fireWare;
    console.log("保存的地址--》",path);
    createDirPath(path).then(function (res) {
      update(resolve,reject)
    }).catch(function (err) {
      console.log(err)
    })
  })
}

function readUnzipFile(fileName){
  if(rootPath==null){
    return;
  }
  fm.readFile({
    filePath: localUnzipFilePath + "/" + fileName,
    success:function(res) {
      if (fileName.indexOf(".dat") != -1) {
        dfuPackage.datData = res.data;
      }else if(fileName.indexOf(".bin") != -1) {
        dfuPackage.binData = res.data;
        getApp().globalData._that.setData({
           binFileSize : res.data.length
        });
      }else {
      }
    }
  })
}
function unzipFile(){
  if(rootPath==null){
    return;
  }
  fm.rmdir({
    dirPath: localUnzipFilePath,
    recursive:true,
    complete: function (res) {
      console.log("删除之前解压的文件",res);
      fm.unzip({
        zipFilePath: localFilePath,
        targetPath: localUnzipFilePath,
        success: function (res) {
          console.log("解压缩文件完成", res);
          //获取解压后的文件
          fm.readdir({
            dirPath: localUnzipFilePath,
            success: function (res) {
              let files = res.files;
              for (var i = 0; i < files.length; i++) {
                let name = files[i];
                readUnzipFile(name);
              }
              console.log("升级文件解压完成,启动升级。。")
            },
            fail: function (err) {

            }
          })
        },
        fail: function (err) {
          console.log("解压缩文件失败", err);
        }
      })
    }
  });

}

function update(resolve, reject) {
  if(rootPath==null){
    return;
  }
  getApp().executeRequest(function (header) {

    wx.downloadFile({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + "/drive_firmware/download?mac=" + app.globalData.upgradeMac,
      header:header,
      success: function (res) {
        console.log("下载完成", res);
        var tempFilePath = res.tempFilePath
        //这里有个坑，真机调试时，我在ios上下载zip包，和服务器上一模一样
        //但在Android上操作时，会多出7个字节，只能强制删除这七个字节
        //Android只有真机调试会出现，预览和体验版的时候不会，暂时不知道原因
        fm.readFile({
          filePath: tempFilePath,
          success: function (fileRes) {
            console.log("读取临时文件成功", fileRes);
            fm.unlink({
              filePath: localFilePath,
              complete: function (res) {
                console.log("删除文件完成,开始存储新文件", res);
                fm.writeFile({
                  filePath: localFilePath,
                  data: fileRes.data,
                  success: function (res) {
                    console.log("存储成功", res)
                    resolve(res);
                  },
                  fail: function (err) {
                    console.log("存储失败", err)
                    reject(err);
                  }
                })
              }
            })
          },
          fail: function (err) {
            console.error("读取临时文件错误", err);
            reject(err);
          }
        })


      },
      fail: function (err) {
        console.log("下载失败", err);
        reject(err);
      }
    });

  });
  
}

function createDirPath(dirPath) {
  return new Promise((resolve, reject) => {
    fm.access({
      path: dirPath,
      success: function (res) {
        resolve(res)
      },
      fail: function (res) {
        fm.mkdir({
          dirPath: dirPath,
          recursive: true,
          success: function (res) {
            resolve(res)
          },
          fail: function (res) {
            console.log(res)
            reject(res)
          }
        })
      }
    })
  })
}

module.exports = {
  downloadZip: downloadZip,
  unzipFile: unzipFile,
  dfuPackage: dfuPackage
}
